
package cn.cxy.viewpager2demo;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayout.Tab;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private ArrayList<String> titleList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TabLayout tab = (TabLayout) findViewById(R.id.tab);
        ViewPager2 vp2 = (ViewPager2) findViewById(R.id.vp2);
        Fragment1 fragment1 = new Fragment1();
        Fragment2 fragment2 = new Fragment2();
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(fragment1);
        fragments.add(fragment2);
//        vp2.setRotation(-90);
        //设置上下滑动
        vp2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
        //设置标题
        titleList.add("第一页");
        titleList.add("第二页");
        //定义适配器
        //设置自定义的适配器必需继承FragmentStateAdapter
        MyAdapter myAdapter = new MyAdapter(this, fragments, titleList);
        vp2.setAdapter(myAdapter);
        //通过TabLayoutMediator 方法参数类型 tablayout   viewpager  new new TabLayoutMediator.TabConfigurationStrategy()
        //tab赋值.settext(集合.get（position）)
        new TabLayoutMediator(tab, vp2, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull Tab tab, int position) {
                tab.setText(titleList.get(position));
            }
        }).attach();
    }
}